package com.jingyanzi.finance.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.jingyanzi.finance.service.IBillService;
import com.jingyanzi.finance.service.ICashierService;
import com.jingyanzi.finance.service.IPayRecordService;
import com.jingyanzi.finance.service.IPlaceService;
import com.jingyanzi.finance.service.IRefundService;
import com.jingyanzi.finance.service.IStatisticsService;




public class FinanceFactory {
	
	private static AtomicBoolean isInit = new AtomicBoolean(false);
	
	private static AtomicBoolean isTest = new AtomicBoolean(false);
	
	private static ApplicationContext context = null;
	
	
	public static void initCofing() {
		Properties properties = new Properties();
		InputStream in = FinanceFactory.class.getClassLoader().getResourceAsStream("application.properties");
		try {
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String value = properties.getProperty("run.test");
		if(value.equals("on")) {
			isTest.set(true);
		}
		if (!isInit.get()) {
			if(isTest.get()) {
				context = new FileSystemXmlApplicationContext(
						"classpath:finance-test-application.xml");
				System.out.println("init test application.xml");
			} else {
				context = new FileSystemXmlApplicationContext(
						"classpath:finance-application.xml");
				System.out.println("init application.xml");
			}
			isInit.set(true);
		}	
	}

	public static IBillService getBillService() {
		initCofing();
		IBillService billService = (IBillService) context.getBean("billService");
		return billService;
	}
	
	public static IStatisticsService getIStatisticsService() {
		initCofing();
		IStatisticsService statisticsService = (IStatisticsService) context.getBean("statisticsService");
		return statisticsService;
	}
	
	public static IPayRecordService getIPayRecordService() {
		initCofing();
		IPayRecordService payRecordService = (IPayRecordService) context.getBean("payRecordService");
		return payRecordService;
	}
	
	public static IPlaceService getIPlaceService() {
		initCofing();
		IPlaceService placeService = (IPlaceService) context.getBean("placeService");
		return placeService;
	}
	
	public static IRefundService getIRefundService() {
		initCofing();	
		IRefundService refundService = (IRefundService) context.getBean("refundService");
		return refundService;
	}
	
	public static ICashierService getICashierService() {
		initCofing();
		ICashierService cashierService = (ICashierService) context.getBean("cashierService");
		return cashierService;
	}
	
}
